/*

  The MIT License

  Copyright (c) 2008 - 2011. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.display.ui
{

import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.events.Event;
import flash.geom.Rectangle;

import ru.goodcore.core.CanvasTracer;
import ru.goodcore.core.ILayoutTracer;
import ru.goodcore.display.ui.core.SizeDependet;
import ru.goodcore.display.ui.core.UIComponent;

/**
 * 
 */
public class GraffitiContainer extends UIComponent {

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function GraffitiContainer() {
		super();
		super.size.offset(100, 100);

		this.viewPort.width = super.size.x;
		this.viewPort.height = super.size.y;

		super.sizeChanged = true;
		this.clipContent = true;
	}

	//-------------------------------------------------------------------------
	//
	//   Variables & const
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */	
	protected const viewPort:	Rectangle = new Rectangle();

	//-------------------------------------------------------------------------
	//
	//   Overridden properties:	DisplayObject
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private var _graphicsChanged:	Boolean = false;

	//---------------------------------
	//  lineColor
	//---------------------------------
	/**
	 * @private
	 */
	private var _lineColor:		uint = 0x00FF00;

	public function set lineColor(value:uint):void {
		if (this._lineColor === value) return;
		this._lineColor = value;
		this._graphicsChanged = true;
		super.invalidate();
	}

	public function get lineColor():uint {
		return this._lineColor;
	}

	//---------------------------------
	//  bgColor
	//---------------------------------
	/**
	 * @private
	 */
	private var _bgColor:		uint = 0xFF0000;

	public function set bgColor(value:uint):void {
		if (this._bgColor === value) return;
		this._bgColor = value;
		this._graphicsChanged = true;
		super.invalidate();
	}

	public function get bgColor():uint {
		return this._bgColor;
	}

	//---------------------------------
	//  clipContent
	//---------------------------------
	/**
	 * @private
	 */
	private var _clipContent:			Boolean = false;
	private var _clipContentChanged:	Boolean = false;

	public function set clipContent(value:Boolean):void {
		if (this._clipContent === value) return;
		this._clipContent = value;
		this._clipContentChanged = true;
		super.invalidate();
	}

	public function get clipContent():Boolean {
		return this._clipContent;
	}

	//---------------------------------
	//   layoutTracer
	//---------------------------------
	/**
	 * @private 
	 */	
	private var _layoutTracer:	ILayoutTracer;

	protected function set layoutTracer(value:ILayoutTracer):void {
		if (this._layoutTracer === value)
			return;

		this._layoutTracer = value;
		this.invalidate();
	}

	protected function get layoutTracer():ILayoutTracer {
		if (!this._layoutTracer)
			this._layoutTracer = new CanvasTracer();

		return this._layoutTracer;
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Overridden methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc 
	 */
	public override function addChild(child:DisplayObject):DisplayObject {
		if (child) {
			if (child.parent && child.parent == this) {
				// У него уже есть RESIZE листенер 
			} else {
				child.addEventListener(Event.RESIZE, this.handler_childResized);
			}
		}

		return this.$addChild(child);
	}

	/**
	 * @private
	 */
	private function $addChild(child:DisplayObject):DisplayObject {
		// Invalid size
		return super.addChild(child);
	}

	/**
	 * @inheritDoc 
	 */
	public override function removeChild(child:DisplayObject):DisplayObject {
		if (child) {
			if (child.parent && child.parent == this) { 
				child.removeEventListener(Event.RESIZE, this.handler_childResized);
			}
		}

		return this.removeChild(child);
	}

	/**
	 * @private
	 */
	private function $removeChild(child:DisplayObject):DisplayObject {
		// Invalid size
		return super.removeChild(child);
	}




	public override function invalidate():void {
		super.invalidate();

		var numChildren:	uint = super.numChildren;
		var child:			UIComponent;

		while (numChildren--) {
			child = super.getChildAt(numChildren) as UIComponent;
			if (child)
				child.invalidate();
		}

	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	private function measureChildren():void {
		var numChildren:	uint = super.numChildren;
		var child:			UIComponent;
		while (numChildren--) {
			
		}
	}

	//-------------------------------------------------------------------------
	//
	//   Public methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	public override function validate():void {
		super.validate();
		trace('GraffitiContainer # validate');

		if ( super.styleChanged ) {
			this.layoutTracer.layoutObjects(this);
		}

		if ( super.sizeChanged ) {

			if (
				   super.widthDependent == SizeDependet.CHILD
				|| super.heightDependent == SizeDependet.CHILD
			) {
				
			}

			// Необходимо скорректировать размеры детей

			super.sizeChanged = false;
		/*
			// Validate self first
			if (super.numChildren)
				this.layoutTracer.layoutObjects(this);

			var parent:GraffitiContainer = super.parent as GraffitiContainer;

			// Invalidate parent
			if (parent) // let the parent relayout us 
				(parent as GraffitiContainer).invalidateChildList();
		*/

		}

		// Изменился стиль заливок
		if ( this._graphicsChanged ) {
			this._graphicsChanged = false;
			const g:Graphics = super.graphics;
			g.clear();
			//g.lineStyle(1, this._lineColor, 1);
			g.beginFill(this._bgColor, 1);
			g.drawRect(0, 0, super.width, super.height);
			g.endFill();
		}

		if ( this._clipContentChanged ) {
			if (this._clipContent) {
				var rect:Rectangle = super.scrollRect;
				if (rect) {
					rect.width = super.size.x;
					rect.height = super.size.y;
					super.scrollRect = rect;
				} else {
					rect = new Rectangle(0, 0, super.size.x, super.size.y);
					super.scrollRect = rect;
				}
			} else {
				super.scrollRect = null;
			}
		}

	}

	/**
	 * 
	 * 
	 */	
	public function invalidateChildList():void {
		this.layoutTracer.layoutObjects(this);
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------

	private function handler_childResized(event:Event):void {
		trace('handler_childResized', super.name);
		if ( // Необходимо скорректировать свои размеры
			   super.widthDependent == SizeDependet.CHILD
			|| super.heightDependent == SizeDependet.CHILD
		) {
			super.invalidate();
		} else {
			// Размер этого компонента не зависит от положения и размеров детей.
			// Остановим всплытие события.
			event.stopImmediatePropagation();
		}
	}

}
}